﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace SMS.Core.Classes
{
    public class XmlSetting
    {
        public XmlSetting(string xmlFileName)
        {
            XmlFileName = xmlFileName;
        }

        #region 成员属性

        public string XmlFileName { get; set; }

        private XmlFile m_CurrentXml;
        public XmlFile CurrentXml
        {
            get
            {
                if (m_CurrentXml == null)
                {
                    if (!File.Exists(XmlFileName))
                    {
                        throw new ApplicationException(string.Format("文件“{0}”不存在。", XmlFileName));
                    }
                    m_CurrentXml = new XmlFile(XmlFileName);
                }
                return m_CurrentXml;
            }
        }

        #endregion

        public void Save()
        {
            CurrentXml.SaveXmlFile();
        }

        public XmlNode GetNodeWithAttribute(string xmlPath, string attKey, string attValue)
        {
            if (string.IsNullOrEmpty(xmlPath) || string.IsNullOrEmpty(attKey) || attValue == null) return null;

            var nodeList = CurrentXml.GetNodeList(xmlPath);
            if (nodeList == null || nodeList.Count == 0) return null;
            foreach (XmlNode node in nodeList)
            {
                try
                {
                    var xmlAtt = node.Attributes[attKey];
                    if (xmlAtt == null) continue;
                    if (xmlAtt.Value.ToLower() == attValue.ToLower()) return node;
                }
                catch
                {
                    continue;
                }
            }
            return null;
        }

        public XmlNode GetFirstNode(string xmlPath)
        {
            var nodeList = CurrentXml.GetNodeList(xmlPath);
            if (nodeList == null || nodeList.Count == 0) return null;
            return nodeList[0];
        }

        public XmlNode GetNodeWithPath(string xmlPath)
        {
            var rNode = CurrentXml.FindNode(xmlPath);
            return rNode;
        }

        public string GetNodeAttribute(XmlNode node, string attKey)
        {
            if (node == null || string.IsNullOrEmpty(attKey)) return null;
            var xmlAtt = node.Attributes[attKey];
            if (xmlAtt != null) return xmlAtt.Value;
            return null;
        }

        public void SetNodeAttribute(XmlNode node, string attKey, string attValue)
        {
            if (node == null || string.IsNullOrEmpty(attKey) || attValue == null) return;
            node.Attributes[attKey].Value = attValue;
        }

        public void SetNodeInnerText(XmlNode node, string innerText)
        {
            if (node == null) return;
            node.InnerText = innerText;
        }
    }
}
